//
//  JPBaseViewController.m
//  JPProjectConfigureDemo
//
//  Created by Carpenter on 2018/2/6.
//  Copyright © 2018年 carpenter. All rights reserved.
//

#import "JPBaseViewController.h"
#import <Masonry/Masonry.h>
#import <SDWebImage/SDImageCache.h>
#import <FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h>
#import "JPBaseCell.h"
#import "UIImage+JPImage.h"
#import "NSObject+Params.h"
#import <objc/runtime.h>

@interface JPBaseViewController ()

@property (nonatomic ,strong ,readwrite)UITableView * tableView;

@property (nonatomic ,assign ,readwrite) NSInteger totalPage;

@end

@implementation JPBaseViewController


 
//MARK: - CycleLift
- (instancetype)init
{    if (self = [super init]) {
        self.hidesBottomBarWhenPushed = true;
    }
    return self;
}
- (instancetype)initWithParams:(NSDictionary *)params{
    if (self = [super initWithParams:params]) {
        
        self.hidesBottomBarWhenPushed = true;
    }
    return self;
}
-(instancetype)initWithTableStyle:(UITableViewStyle)tableStyle{
    if (self = [super init]) {
 
        self.hidesBottomBarWhenPushed = true;

    }
    return self;
}
 
- (void)viewDidLoad {
    [super viewDidLoad];

    self.fd_prefersNavigationBarHidden = [self jp_isNeedHiddenNavigationBar];
    
    self.view.backgroundColor = [UIColor colorWithRed:245.0/255 green:246.0/255 blue:248.0/255 alpha:1];
    
    self.currentPage = 1;
    
    self.pageSize = 10;
    
    self.pageSize = 10;
    self.currentPage = 1;
    self.totalPage = 1;
    
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    self.automaticallyAdjustsScrollViewInsets = false;
    
    self.definesPresentationContext = true;//UISearchController添加到tabkeHeaderView上，点击搜索框消失
    
    [self jp_configure];
    
    [self jp_overloadNavItems];
    
    [self jp_setupUI];
    
    [self jp_requestData];
}

-(void)jp_configure{}
-(void)jp_overloadNavItems{}
-(void)jp_setupUI{}
-(void)jp_requestData{}


-(BOOL)jp_isNeedHiddenNavigationBar{
    return false;
}
-(UITableViewStyle)jp_tableStyle{
    return UITableViewStyleGrouped;
}


-(void)jp_updateTotalPageWithTotal:(NSInteger)total{
    
    if(self.pageSize <= 0) return;
    
    self.totalPage = total / self.pageSize;
    
    if (total % self.pageSize > 0) {
    
        self.totalPage = self.totalPage + 1;
    }
}

//MARK: - <内存警告>
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
//    [JPHUD showProgress:@"系统内存空间不足，正在为您清除缓存文件"];
    
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
        
//        [JPHUD showSuccess:@"已帮您清理了缓存文件!"];
        
    }];
    
}

//MARK: - 默认所有都不支持转屏,如需个别页面支持除竖屏外的其他方向，请在viewController重新下边这三个方法
// 是否支持自动转屏
- (BOOL)shouldAutorotate {
    return false;
}
// 返回你的屏幕支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
// 默认的屏幕方向（当前ViewController必须是通过模态出来的UIViewController（模态带导航的无效）方式展现出来的，才会调用这个方法）
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

//MARK: - <UITableViewDataSource>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 0;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [JPBaseCell jp_cellForTableView:tableView];
}
//MARK: - <UITableViewDelegate>
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
//MARK: - <UIScrollViewDelegate>
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [[UIApplication sharedApplication].delegate.window endEditing:true];
}
//MARK: - <DZNEmptyDataSetSource>
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamedFromJPBundle:@"no_data_img"];
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView{
    NSMutableAttributedString * titleAttributedStr = [[NSMutableAttributedString alloc] initWithString:@"暂无数据" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:22]}];
    return titleAttributedStr;
}
//MARK: - <DZNEmptyDataSetDelegate>
- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView{
    return true;
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return true;
}

//MARK: - Getter
-(NSMutableArray *)sourceArrayM{
    if (!_sourceArrayM) {
        _sourceArrayM = [NSMutableArray array];
    }
    return _sourceArrayM;
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:[self jp_tableStyle]];
        _tableView.backgroundColor = self.view.backgroundColor;
        _tableView.estimatedRowHeight = 60;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.emptyDataSetSource = self;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, CGRectGetHeight([UIApplication sharedApplication].statusBarFrame) <= 20 ? 20 : 34 + 20)];
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
        }];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
    }
    return _tableView;
}

@end


#ifdef DEBUG

@interface UIViewController (JPSwizzling)

@end

@implementation UIViewController (JPSwizzling)

+(void)load{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        methodSwizzling([UIViewController class], NSSelectorFromString(@"dealloc"), @selector(swzzling_jp_dealloc));
    });
    
}

void methodSwizzling(Class class,SEL originSel,SEL overrideSel)
{
    Method originMethod = class_getInstanceMethod(class, originSel);
    Method overrideMethod = class_getInstanceMethod(class, overrideSel);
    
    if (class_addMethod(class,
                        originSel,
                        method_getImplementation(overrideMethod),
                        method_getTypeEncoding(originMethod)))
    {
        /** case1:NSMutableDictionary中没有-setObject:forKey:的实现 */
        class_replaceMethod(class,
                            overrideSel,
                            method_getImplementation(originMethod),
                            method_getTypeEncoding(originMethod));
    }else{
        /** case2:NSMutableDictionary中有-setObject:forKey:的实现   */
        method_exchangeImplementations(originMethod, overrideMethod);
    }
}

- (void)swzzling_jp_dealloc{
    
    NSLog(@"\ndealloc -- %@\n",self);
    [self swzzling_jp_dealloc];
}


@end

#else

#endif
